/**
 *  类型转换处理工具类
 *  @Authors: LiRui
 *  @date 2017-09-14
 *
 */

var TypeUtils = {

    chnNumChar: ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"],
    chnUnitSection: ["", "万", "亿", "万亿", "亿亿"],
    chnUnitChar: ["", "十", "百", "千"],

    // 阿拉伯数字123转中文一二三
    SectionToChinese: function (section) {
        var strIns = '', chnStr = '';
        var unitPos = 0;
        var zero = true;
        while (section > 0) {
            var v = section % 10;
            if (v === 0) {
                if (!zero) {
                    zero = true;
                    chnStr = TypeUtils.chnNumChar[v] + chnStr;
                }
            } else {
                zero = false;
                strIns = TypeUtils.chnNumChar[v];
                strIns += TypeUtils.chnUnitChar[unitPos];
                chnStr = strIns + chnStr;
            }
            unitPos++;
            section = Math.floor(section / 10);
        }
        return chnStr;
    },
    // 阿拉伯数字123转中文一二三 将一十转化为十
    NumberToChinese: function (num) {
        var unitPos = 0;
        var strIns = '', chnStr = '';
        var needZero = false;
        if (num === 0) {
            return TypeUtils.chnNumChar[0];
        }
        while (num > 0) {
            var section = num % 10000;
            if (needZero) {
                chnStr = TypeUtils.chnNumChar[0] + chnStr;
            }
            strIns = TypeUtils.SectionToChinese(section);
            strIns += (section !== 0) ? TypeUtils.chnUnitSection[unitPos] : TypeUtils.chnUnitSection[0];
            chnStr = strIns + chnStr;
            needZero = (section < 1000) && (section > 0);
            num = Math.floor(num / 10000);
            unitPos++;
        }
        if (chnStr.indexOf("一十") === 0) {
            chnStr = chnStr.replace("一十", "十");
        }
        return chnStr;
    },

    NumberToMoney: function (n) {
        if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n))
            return "数据非法";
        var unit = "千百拾亿千百拾万千百拾元角分", str = "";
        n += "00";
        var p = n.indexOf('.');
        if (p >= 0)
            n = n.substring(0, p) + n.substr(p + 1, 2);
        unit = unit.substr(unit.length - n.length);
        for (var i = 0; i < n.length; i++)
            str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i);
        return str.replace(/零(千|百|拾|角)/g, "零").replace(/(零)+/g, "零").replace(/零(万|亿|元)/g, "$1").replace(/(亿)万|壹(拾)/g, "$1$2").replace(/^元零?|零分/g, "").replace(/元$/g, "");
    }
};


